FROM node:20.12.0-slim AS base

FROM base AS deps
RUN apt-get install -y libc6 && apt-get clean
WORKDIR /www
COPY package.json yarn.lock ./
RUN yarn --pure-lockfile

FROM base AS builder
WORKDIR /www

# Environment variables must be present at build time
# https://github.com/vercel/next.js/discussions/14030
ARG NEXT_PUBLIC_API_HOST
ENV NEXT_PUBLIC_API_HOST=${NEXT_PUBLIC_API_HOST}

COPY --from=deps /www/node_modules ./node_modules
COPY src ./src
COPY public ./public
COPY package.json next.config.mjs tsconfig.json tailwind.config.ts postcss.config.mjs ./
RUN yarn build

FROM base AS runner
WORKDIR /www

RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs
USER nextjs

COPY --from=builder /www/public ./public
COPY --from=builder --chown=nextjs:nodejs /www/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /www/.next/static ./.next/static

# Environment variables must be redefined at run time
ARG NEXT_PUBLIC_API_HOST
ENV NEXT_PUBLIC_API_HOST=${NEXT_PUBLIC_API_HOST}

CMD ["node", "server.js"]